package com.situ.web.servlet;

import com.situ.web.pojo.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;
import com.situ.web.util.JSONUtil;
import com.situ.web.util.MD5Util;
import com.situ.web.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        switch (method) {
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        //退出销毁session里面的登录凭证
        session.invalidate();
        resp.sendRedirect("/login.jsp");
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        //1.先判断验证码是不是正确
        //2.验证码错误，返回错误提示信息：验证码错误
        //3.验证码正确，再验证用户名和密码是否正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name, MD5Util.MD5Encode(password));
        /*if (user.status == 0) {
            JSONUtil.toJSON(resp, Result.error("该用户已经被禁用"));
            return;
        }*/


        if (user != null) {//登录成功，重定向到首页
            //这个用户登录成功这个凭证放到session
            session.setAttribute("user", user);

            // http://localhost:8080/
            // http://localhost:8080/index.jsp
            //resp.sendRedirect("/");
            //req.getRequestDispatcher("/").forward(req, resp);
            JSONUtil.toJSON(resp, Result.ok("登录成功"));
        } else {//登录失败，重定向到登录界面
            //resp.sendRedirect("/login.jsp");
            //resp.sendRedirect("/fail.jsp");
            JSONUtil.toJSON(resp, Result.error("登录失败"));
        }
    }
}
